package pl.th.permission.demo.example;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import java.io.File;
import java.util.StringJoiner;

import pl.th.permission.PermissionCompat;
import pl.th.permission.annotation.NeedPermission;
import pl.th.permission.annotation.OnAllPermissionsGranted;
import pl.th.permission.annotation.OnAnyPermissionsDenied;
import pl.th.permission.annotation.OnPermissionGranted;
import pl.th.permission.demo.BuildConfig;

/**
 *
 * Need to copy an apk named "app-release.apk" to {@link Environment#DIRECTORY_DOWNLOADS} in
 * {@link Environment#getExternalStorageDirectory()}
 */
public class InstallAppActivity extends BaseActivity {

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println(PermissionCompat.isWriteSettingPerGranted(this));
        startInstall();
    }

    @NeedPermission(
            requestCode = 100,
            permissions = {
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.MANAGE_EXTERNAL_STORAGE,
                    Manifest.permission.REQUEST_INSTALL_PACKAGES,
            }
    )
    @OnAllPermissionsGranted(requestCode = 100)
    private void startInstall() {
        File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File file = new File(directory.getAbsolutePath() + "/app-release.apk");
        Uri apkUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        install.setDataAndType(apkUri, "application/vnd.android.package-archive");
        startActivity(install);
    }

    @OnAnyPermissionsDenied(requestCode = 100)
    private void forbiddenInstall(String[] permissions) {
        Toast.makeText(this, "any denied: " + permissions[0], Toast.LENGTH_SHORT).show();
    }

    @OnPermissionGranted(
            requestCode = 100,
            permissions = {
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.MANAGE_EXTERNAL_STORAGE
            }
    )
    private void forbiddenInstall() {
        Toast.makeText(this, "granted: " + Manifest.permission.READ_EXTERNAL_STORAGE, Toast.LENGTH_SHORT).show();
    }

}
